package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.study.entity.Course;
import com.xmy.study.entity.EduShutnumVideo;
import com.xmy.study.entity.EduVideo;
import com.xmy.study.entity.ExcelDto.ShutNumDto;
import com.xmy.study.entity.Shutnum;
import com.xmy.study.mapper.ShutnumMapper;
import com.xmy.study.service.*;
import com.xmy.study.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import java.util.regex.Pattern;

/**
 * <p>
 * 关数 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-09-08
 */
@RestController
@RequestMapping("/api/admin/shutnum")
public class ShutnumController {

    @Autowired
    IdWorker idWorker;

    @Autowired
    ShutnumMapper eduShutnumMapper;


    @Autowired
    IShutnumService eduShutnumService;


    @Autowired
    IShutnumService iEduShutnumService;

    @Autowired
    ICourseService iEduCourseService;


    @Autowired
    IEduVideoService eduVideoService;
    @Autowired
    IEduShutnumVideoService eduShutnumVideoService;

    @GetMapping("getShutnum")
    @ApiOperation("查询关数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = false, dataType = "String"),
    })
    public Result searchShutNum(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Shutnum> iPage = new Page<>(pageNum, pageSize);
        String name = (String) reMap.get("name");
        String courseId = (String) reMap.get("courseId");
        if (StringUtils.isBlank(courseId)) {
            return new Result(Code.ERROR, "", "课程id不能为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        eduShutnumService.page(iPage, queryWrapper);
        for (Shutnum eduShutnum: iPage.getRecords()) {
            QueryWrapper<EduVideo> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.inSql("id", "SELECT vedio_id FROM edu_shutnum_video WHERE course_id = " + eduShutnum.getCourseId() + " AND shutnum_id = " + eduShutnum.getId() + " AND deleted = 0");
            List<EduVideo> list = eduVideoService.list(objectQueryWrapper);
            eduShutnum.setVideoList(list);
        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @DeleteMapping("delShutnum")
    @ApiOperation("删除关数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String")
    })
    public Result delShutNum(@RequestParam("id") String id) {
        Shutnum eduShutnum = iEduShutnumService.getById(id);
        if (eduShutnum == null) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该关数不存在");
        }
        eduShutnumService.removeById(id);
        return new Result(Code.OK, null, "关数信息删除成功~");
    }

    @DeleteMapping("/batchShutnum")
    @ApiOperation("批量删除关数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String")
    })
    public Result batchDelShutNum(@RequestParam("id") List idList) {
        for (Object id : idList) {
            Shutnum eduShutnum = iEduShutnumService.getById((Serializable) id);
            if (Objects.isNull(eduShutnum)) {
                return new Result(Code.EXP_ERROR, Code.EXP_MSG, id + "：该关数不存在");
            }
        }
        eduShutnumService.removeByIds(idList);
        //TODO：删除完关卡后重新排序 待完善
        return new Result(Code.DELETE_OK, Code.DELETE_OK_MSG, "批量删除关数成功~");
    }

    @PostMapping("newShutnum")
    @ApiOperation("新增关数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "num", value = "关数", required = false, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sort", value = "排序", required = false, dataType = "String")
    })
    public Result saveShutNum(@RequestBody Shutnum eduShutnum) {
        eduShutnum.setId(idWorker.nextId());
        eduShutnumService.save(eduShutnum);
        return new Result(Code.OK, null, "关卡信息新增成功~");
    }
    @PostMapping("updateShutnum")
    @ApiOperation("修改关数信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "关数id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "num", value = "关数", required = false, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sort", value = "排序", required = false, dataType = "String")
    })
    public Result updateShutNum(@RequestBody Map reMap) {
        String id = (String) reMap.get("id");
        String name = (String) reMap.get("name");
        String courseId = (String) reMap.get("courseId");
        String num = (String) reMap.get("num");
        String sort = (String) reMap.get("sort");
        Course course = iEduCourseService.getById(Long.valueOf(courseId));
        if (course == null) {
            return new Result(Code.ERROR, "", "课程不存在");
        }
        Shutnum eduShutnum = eduShutnumService.getById(Long.valueOf(id));
        if (Objects.isNull(eduShutnum)) {
            return new Result(Code.SAVE_ERROR, Code.SAVE_ERROR_MSG, "该关数不存在");
        }
        //判断是否为数字 数字：true 非数字：false
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        eduShutnum.setName(name);
        if (StringUtils.isNotBlank(courseId)) {
            eduShutnum.setCourseId(Long.valueOf(courseId));
        }
        if (StringUtils.isNotBlank(num)) {
            Boolean numB = pattern.matcher(num).matches();
            if (!numB) {
                return new Result(Code.SAVE_ERROR, Code.SAVE_ERROR_MSG, "请正确输入关数，例如：1");
            }
            eduShutnum.setNum(Integer.valueOf(num));
        }
        if (StringUtils.isNotBlank(sort)) {
            Boolean sortB = pattern.matcher(sort).matches();
            if (!sortB) {
                return new Result(Code.SAVE_ERROR, Code.SAVE_ERROR_MSG, "请正确输入排序，例如：1");
            }
            eduShutnum.setSort(Integer.valueOf(sort));
        }
        QueryWrapper<Shutnum> eduShutnumQueryWrapper = new QueryWrapper<>();
        eduShutnumQueryWrapper.eq("course_id", courseId);
        eduShutnumQueryWrapper.eq("status", 1);
        Long allShutNum = iEduShutnumService.count(eduShutnumQueryWrapper);
        course.setAllShutNum(Integer.parseInt(allShutNum.toString()));
        eduShutnumService.updateById(eduShutnum);
        return new Result(Code.OK, null, "关数信息修改成功~");
    }


    @PostMapping("/readShutNum")
    @ApiOperation("关数导入，读取关数excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "需要读取的单元excel文件", required = true, dataType = "MultipartFile"),
            @ApiImplicitParam(name = "courseId", value = "课程id", required = true, dataType = "String")
    })
    public Result readShutNum(MultipartFile file, String courseId) {
        //try {

        Course course = iEduCourseService.getById(courseId);
        if (course == null) {
            return new Result(Code.ERROR, "", "课程不存在");
        }

        List<T> list = ExcelUtil.importExcel(file, ShutNumDto.class, 1);
        Integer rightCount = 0;
        String unitNames = "";
        for (Object object : list) {
            ShutNumDto shutNumDto = (ShutNumDto) object;
            QueryWrapper queryWrapper;
            unitNames = shutNumDto.getUnitNames().trim();
            //字符转为中文
            unitNames = SymbolConversionUtils.englishToChineseString(unitNames);
            String[] repairso = unitNames.split("，");

            for (int a = 0; a < repairso.length; a++) {
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", repairso[a].trim());
                queryWrapper.eq("course_id", courseId);
                queryWrapper.last("limit 1");

                queryWrapper.clear();
            }

            Shutnum eduShutnumExist = eduShutnumMapper.selectByName(shutNumDto.getName().trim(), courseId);
            Shutnum eduShutnum = new Shutnum();
            eduShutnum.setName(shutNumDto.getName().trim());
            eduShutnum.setCourseId(Long.valueOf(courseId));

            eduShutnum.setSort(shutNumDto.getSort());
            eduShutnum.setNum(shutNumDto.getSort());

            eduShutnum.setId(idWorker.nextId());
            if (Objects.isNull(eduShutnumExist)) {
                eduShutnumService.save(eduShutnum);
            } else {
                eduShutnum.setId(eduShutnumExist.getId());
                eduShutnumService.updateById(eduShutnum);
            }
            rightCount++;
        }

        Map<String, String> map = new HashMap<>();
        map.put("rightCount", rightCount.toString());

        QueryWrapper<Shutnum> eduShutnumQueryWrapper = new QueryWrapper<>();
        eduShutnumQueryWrapper.eq("course_id", courseId);
        eduShutnumQueryWrapper.eq("status", 1);

        Long allShutNum = iEduShutnumService.count(eduShutnumQueryWrapper);
        course.setAllShutNum(Integer.parseInt(allShutNum.toString()));
        iEduCourseService.updateById(course);

        //已经导入的关卡数集合
        List<Integer> integers = eduShutnumService.getNumList(courseId);
        //转为数组
        Integer[] array = integers.toArray(new Integer[integers.size()]);
        StringBuffer sb = new StringBuffer();
        Hashtable<Object, Object> hashtable = new Hashtable<>();
        //获取连续数字中缺少的数字（没有导入的关卡数）
        for (int i = 0; i <= array.length - 1; i++) {
            hashtable.put(array[i], 1);
        }
        for (int i = 1; i <= array[array.length - 1]; i++) {
            if (hashtable.get(i) == null) {
                sb.append(i);
                sb.append("，");
            }
        }

        //去除最后一个字符
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        map.put("errorShutNum", sb.toString());

        //获取最后一个关卡数（应该导入的关卡总数）
        Integer countId = eduShutnumService.getCountNum(courseId);
        map.put("endNum", String.valueOf(countId));

        return new Result(Code.OK, map, "导入数据成功");
        //} catch (Exception e) {
        //return new Result(Code.ERROR,null,"导入数据失败！");
        //}
    }

    @GetMapping("videoList")
    @ApiOperation("视频-获取视频列表")
    public Result videoList(@RequestParam Map reMap) {
        String courseId = (String) reMap.get("courseId");
        String shutnumId = (String) reMap.get("shutnumId");
        int pageNum = StringUtils.isEmpty((CharSequence) reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum").toString());
        int pageSize = StringUtils.isEmpty((CharSequence) reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize").toString());

        IPage<EduVideo> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper queryWrapperShutNum = new QueryWrapper<>();
        queryWrapperShutNum.select("GROUP_CONCAT(vedio_id) AS vedioIdS");
        queryWrapperShutNum.eq("course_id", courseId);
        queryWrapperShutNum.eq("shutnum_id", shutnumId);
        List<EduShutnumVideo> sVideoRs = eduShutnumVideoService.list(queryWrapperShutNum);

        String vedioId = sVideoRs.get(0).getVedioIdS();
        String[] vedioIdS = vedioId.split(",");

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", vedioIdS);
        eduVideoService.page(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), "视频列表");
    }

    @GetMapping("/shunNumOfExcel")
    @ApiOperation("导出关数")
    public Result studentOfExcel(@RequestParam(value = "courseId", required = false) String courseId, HttpServletResponse response) {
        if (StringUtils.isBlank(courseId)) {
            return new Result(Code.ERROR, null, "导出失败");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.eq("deleted", 0);
        List<Shutnum> eduShutnumList = eduShutnumService.list(queryWrapper);

        ExcelExportHandleUtil.export(response, "导出关数", eduShutnumList, Shutnum.class);
        return new Result(Code.OK, null, "导出成功");
    }
}
